package com.hangwei.paperless.adapter;

import android.graphics.Color;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hangwei.paperless.R;
import com.hangwei.paperless.model.bean.DRSInfo;
import com.hangwei.paperless.model.bean.RecordListBean;
import com.hangwei.paperless.model.bean.ResultBean;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.view.SealHelper;
import com.hangwei.paperless.widget.URLImageParser;
import com.twelve.all.adapter.MyAdapter;
import com.twelve.all.net.CallBack;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.Tools;

import org.xml.sax.XMLReader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 张龙臣 on 2020/11/11.
 */

public abstract class MainRepairAdapter extends MyAdapter<RecordListBean, BaseViewHolder> {

    private boolean mEnableAll = true;

    /**
     * @param type 0:有折叠箭头，1：没有
     */
    public MainRepairAdapter(@Nullable List<RecordListBean> data, int type) {
        super(type == 0 ? R.layout.item_main_repair : R.layout.item_main_repair1, data);
    }

    public MainRepairAdapter(@Nullable List<RecordListBean> data) {
        super(R.layout.item_main_repair, data);
    }

    @Override
    protected void convert(final BaseViewHolder helper, final RecordListBean item) {
        helper.setIsRecyclable(false);
        LinearLayout llItemView0 = helper.getView(R.id.llItemView0);
//        Log.i(TAG, "convert: "+item.seq+"    isCurrent:"+item.isCurrent+"    isDrsOpen:"+item.isDrsOpen);
        helper.setBackgroundColor(R.id.flUserSeal, !item.isTechnicianNA ? mContext.getResources().getColor(R.color.lightGray) : Color.TRANSPARENT);
        helper.setBackgroundColor(R.id.flInspector, !item.isInspectorNA ? mContext.getResources().getColor(R.color.lightGray) : Color.TRANSPARENT);
//        "<style>p{margin: 0 0;}</style>"
        String source = Tools.checkedString(item.description);
//        String all = source.replaceAll("<p>", "<p  style=\"display:block;margin:0 0;\">");
        //替换掉P标签开头
        String all = source.replaceAll("<p>", "").replaceAll("<p .?>", "");
        while (all.endsWith("</p>")) {
            all = all.substring(0, all.lastIndexOf("</p>"));
        }
        while (all.endsWith("<br/>")) {
            all = all.substring(0, all.lastIndexOf("<br/>"));
        }
        all = all.replaceAll("</p>", "<br/>");
        Spanned html;
        TextView tvDes = helper.getView(R.id.tvDes);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
            html = Html.fromHtml(all, Html.FROM_HTML_MODE_COMPACT, new URLImageParser(tvDes, mContext), new Html.TagHandler() {
                @Override
                public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {

                }
            });
        else
            html = Html.fromHtml(all, new URLImageParser(tvDes, mContext), new Html.TagHandler() {
                @Override
                public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {

                }
            });

        helper.setText(R.id.tvItem, Tools.checkedString(item.item))
                .setText(R.id.tvPowNo, Tools.checkedString(item.seq))
                .setText(R.id.tvDes, html)
        ;
        helper.setGone(R.id.ivFold, item.isDrs || item.isPicture)
                .setOnClickListener(R.id.ivFold, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        item.isDrsOpen = !item.isDrsOpen;
//                        Log.i(TAG, "convert  onClick: "+item.seq+"    isCurrent:"+item.isCurrent+"    isDrsOpen:"+item.isDrsOpen);
                        Animation anim;// 设置动画时间
                        // 设置保持动画最后的状态
                        if (item.isDrsOpen) {
                            anim = new RotateAnimation(0f, -90f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        } else {
                            anim = new RotateAnimation(-90f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        }
                        anim.setFillAfter(true); // 设置保持动画最后的状态
                        anim.setDuration(200); // 设置动画时间
                        helper.getView(R.id.ivFold).startAnimation(anim);
                        initDrs(helper, item);
                    }
                });
        if (item.isDrsOpen) {
            Animation anim = new RotateAnimation(0f, -90f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setFillAfter(true); // 设置保持动画最后的状态
            anim.setDuration(50); // 设置动画时间
            helper.getView(R.id.ivFold).startAnimation(anim);
        }
        RecyclerView recyclerView = helper.getView(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        final ArrayList<ResultBean> resultBeans = new ArrayList<>();
        if (item.resultItems != null)
            for (int i = 0; i < item.resultItems.size(); i++) {
                String str = item.resultItems.get(i);
                if (!TextUtils.isEmpty(str) && str.equals(item.resultVal)) {
                    resultBeans.add(new ResultBean(str, true));
                } else resultBeans.add(new ResultBean(str, false));
            }
        final boolean able = mEnableAll && item.isCurrent;

        if (TextUtils.isEmpty(item.resultId)) helper.setGone(R.id.llResult, false);
        else {
            helper.setGone(R.id.llResult, true);
            recyclerView.setAdapter(new ResultAdapter(resultBeans, able));
        }

        RelativeLayout flUserSeal = helper.getView(R.id.flUserSeal);
        if (item.isNA) {
            helper.setText(R.id.tvNa, Tools.checkedString(item.naTypeCode));
            helper.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.lightGray));
            RelativeLayout flInspector = helper.getView(R.id.flInspector);
            flInspector.removeAllViews();
            SealHelper sealHelper1 = new SealHelper(mContext) {
                @Override
                protected void onSeal() {
                    String resultVal = null;
                    for (ResultBean bean : resultBeans) {
                        if (bean.isChecked)
                            resultVal = bean.name;
                    }
                    seal(item, 2, resultVal);
                }
            };
            sealHelper1.bindData(new SealHelper.SealBean(item.isInspectorNA, item.inspectorStampId, item.inspectorId, item.inspectorStampTypeCode, item.inspectorStampCode, item.inspectorDate, item.inspector, mEnableAll));
            flInspector.addView(sealHelper1.getItemView());
            ImageView ivObliqueLine = helper.getView(R.id.ivObliqueLine);
            ivObliqueLine.setAdjustViewBounds(true);
            ivObliqueLine.setVisibility(View.VISIBLE);
        } else {
            helper.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            flUserSeal.removeAllViews();
            SealHelper sealHelper = new SealHelper(mContext) {
                @Override
                protected void onSeal() {
                    String resultVal = null;
                    for (ResultBean bean : resultBeans) {
                        if (bean.isChecked)
                            resultVal = bean.name;
                    }
                    seal(item, 1, resultVal);
                }

                @Override
                public void onNa() {
                    onNaCurrent(item.id);
                }
            };

            sealHelper.bindData(new SealHelper.SealBean(item.isTechnicianNA, item.technicianStampId, item.technicianId, item.technicianStampTypeCode, item.technicianStampCode, item.technicianDate, item.technician, able, mEnableAll&&TextUtils.isEmpty(item.inspectorId)));
            flUserSeal.addView(sealHelper.getItemView());
            if (item.isTechnicianNA) {
            } else {
                helper.setBackgroundColor(R.id.flUserSeal, mContext.getResources().getColor(R.color.lightGray));
//                helper.setGone(R.id.ivObliqueLine, false);
            }
            RelativeLayout flInspector = helper.getView(R.id.flInspector);
            if (item.isInspectorNA) {
                flInspector.removeAllViews();
                SealHelper sealHelper1 = new SealHelper(mContext) {
                    @Override
                    protected void onSeal() {
                        String resultVal = null;
                        for (ResultBean bean : resultBeans) {
                            if (bean.isChecked)
                                resultVal = bean.name;
                        }
                        seal(item, 2, resultVal);
                    }
                };
                final boolean canSeal = able && (!item.isTechnicianNA || !TextUtils.isEmpty(item.technicianId));
                sealHelper1.bindData(new SealHelper.SealBean(item.isInspectorNA, item.inspectorStampId, item.inspectorId, item.inspectorStampTypeCode, item.inspectorStampCode, item.inspectorDate, item.inspector, canSeal));
                flInspector.addView(sealHelper1.getItemView());
            } else {
                helper.setBackgroundColor(R.id.flInspector, mContext.getResources().getColor(R.color.lightGray));
            }
        }
        if (item.isDrsOpen && (item.isDrs || item.isPicture))
            initDrs(helper, item);
        else helper.setGone(R.id.llDRS, false);

    }

    protected abstract void onNaCurrent(String id);

    protected abstract void seal(RecordListBean item, int stampRole, String resultVal);

    private void initDrs(final BaseViewHolder helper, final RecordListBean item) {
        if (item.isDrsOpen) {
            final DRSAdapter drsAdapter = new DRSAdapter(item.isCurrent);
            RecyclerView recyclerViewDRS = helper.getView(R.id.recyclerViewDRS);
            final RecyclerView recyclerViewPic = helper.getView(R.id.recyclerViewPic);
            recyclerViewDRS.setLayoutManager(new GridLayoutManager(mContext, 2));
            LinearLayoutManager layout = new LinearLayoutManager(mContext);
            layout.setOrientation(LinearLayoutManager.HORIZONTAL);
            recyclerViewPic.setLayoutManager(layout);
            drsAdapter.setCanNa(TextUtils.isEmpty(item.inspectorStampId));
            recyclerViewDRS.setAdapter(drsAdapter);
            final HorizontalPicAdapter picAdapter = new HorizontalPicAdapter(null);
            recyclerViewPic.setAdapter(picAdapter);
            String userId = SPUtil.getString(SPKey.Account.USER_ID);
            StaticPresenter.getDrsAndAttachmentList(userId, item.id, 0, new CallBack<DRSInfo>() {
                @Override
                public void onCompleted(final DRSInfo drsInfo) {
                    if (drsInfo.attachList != null && drsInfo.attachList.size() > 0) {
                        helper.setGone(R.id.recyclerViewPic, true);
                        picAdapter.setNewData(drsInfo.attachList);
                        recyclerViewPic.addOnItemTouchListener(new com.chad.library.adapter.base.listener.OnItemChildClickListener() {
                            @Override
                            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                                if (mEnableAll)
                                showBigPic((ArrayList<String>) picAdapter.getData(), position);
                            }
                        });
                    } else helper.setGone(R.id.recyclerViewPic, false);
                    if (drsInfo.drsList != null && drsInfo.drsList.size() > 0) {
                        drsAdapter.setData(drsInfo.drsList);
                        helper.setGone(R.id.llDRS, true);
                        helper.getView(R.id.tvSave).setEnabled(item.isCurrent && mEnableAll);
                        helper.setGone(R.id.tvSave, item.isCurrent && mEnableAll);
                        helper.setText(R.id.tvTitle, item.isCurrent && mEnableAll ? "填报DRS" : "预览DRS");
                        helper.setOnClickListener(R.id.tvSave, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                onSaveDRS(drsInfo.drsList);
                            }
                        });
                    } else helper.setGone(R.id.llDRS, false);
                }

                @Override
                public void onError() {

                }
            });
        } else {
            helper.setGone(R.id.recyclerViewPic, false)
                    .setGone(R.id.llDRS, false);
        }
    }

    protected abstract void showBigPic(ArrayList<String> data, int position);

    protected abstract void onSaveDRS(List<DRSInfo.DrsBean> drsList);


    public void setEnableAll(boolean enableAll) {
        mEnableAll = enableAll;
    }

}
